import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;

final class NewItem extends AbstractAction{
  private final Doer frame;
  NewItem(String name,Doer frame){
    super(name);
    this.frame=frame;
    putValue(SHORT_DESCRIPTION,name);
    String iconFileName="images"+File.separator+name+".gif";
    if(new File(iconFileName).exists())putValue(SMALL_ICON,new ImageIcon(iconFileName));
  }
  public void actionPerformed(ActionEvent e){
    newFile();
  }
  public void newFile(){
    FileDialog fileDialog=new FileDialog();
    Rectangle bounds=frame.getBounds();
    fileDialog.setLocation(bounds.x+bounds.width/3,bounds.y+bounds.height/3);
    fileDialog.setVisible(true);
  }
  public void newFile(String name){
    FileDialog fileDialog=new FileDialog();
    fileDialog.setNameField(name);
    Rectangle bounds=frame.getBounds();
    fileDialog.setLocation(bounds.x+bounds.width/3,bounds.y+bounds.height/3);
    fileDialog.setVisible(true);
  }
  //class newProject

  final class FileDialog extends JDialog implements ActionListener{
    private final JButton ok,cancel,choose;
    private final JTextField nameField=new JTextField(1),
                     dirField=new JTextField(frame.getDirection(),1);
    private final JTextArea viewArea;
    private final JList typeList;
    private final JFileChooser files=new JFileChooser(new File(frame.getDirection()));

    FileDialog(){
      super(frame,"New File",true);
      setResizable(false);
      //
      JPanel buttonPane=new JPanel();
      buttonPane.add(ok=createButton("OK"));
      buttonPane.add(cancel=createButton("Cancel"));
      getContentPane().add(buttonPane,BorderLayout.SOUTH);
      //dataPanel
      JPanel dataPane=new JPanel();
      GridBagLayout gbLayout=new GridBagLayout();
      dataPane.setLayout(gbLayout);
      GridBagConstraints con=new GridBagConstraints();
      con.fill=GridBagConstraints.HORIZONTAL;
      con.gridwidth=GridBagConstraints.REMAINDER;
      JLabel label=new JLabel("Choose a Type");
      gbLayout.setConstraints(label,con);
      dataPane.add(label);
      //choose type
      String[] typeName={"Common class","Abtract class","Interface","Frame"};
      typeList=new JList(typeName);
      typeList.setValueIsAdjusting(true);
      typeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      typeList.setSelectedValue(typeName[0],true);
      typeList.addListSelectionListener(new ListSelectionListener(){
                                          public void valueChanged(ListSelectionEvent e){
					    if(e.getValueIsAdjusting()){
					      String tempName=nameField.getText();
                                              selectType(tempName.substring(0,tempName.length()-5));
	                                    }
					  }
                                        });
      JScrollPane chooseType=new JScrollPane(typeList);

      //view type
      viewArea=new JTextArea(7,5);
      viewArea.setFont(frame.getFont());
	  viewArea.setTabSize(4);
      JScrollPane viewType=new JScrollPane(viewArea);
      //JSpliPane
      JSplitPane splitPane=new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,chooseType,viewType);
      splitPane.setDividerLocation(80);
      splitPane.setOneTouchExpandable(true);
      gbLayout.setConstraints(splitPane,con);
      dataPane.add(splitPane);
      //namepanel
      JPanel namePane=new JPanel();
      label=new JLabel("File Name:");
      nameField.setText(".java");
      namePane.add(label);
      namePane.add(nameField);
      namePane.setLayout(new FlowLayout(FlowLayout.LEFT));
      gbLayout.setConstraints(namePane,con);
      dataPane.add(namePane);
      //directionPanel
      JPanel dirPane=new JPanel();
      label=new JLabel("Direction: ");
      dirPane.add(label);
      dirPane.add(dirField);
      dirPane.add(choose=createButton(new ImageIcon("images/Open.gif")));
      gbLayout.setConstraints(dirPane,con);
      dataPane.add(dirPane);

      nameField.addCaretListener(new CaretListener(){
                               public void caretUpdate(CaretEvent e) {
			         if(nameField.getText().length()>5)
				   selectType(nameField.getText().substring(0,nameField.getText().length()-5));
	   	               }
	                     });

      nameField.setColumns(30);
      dirField.setColumns(30);
      getContentPane().add(dataPane,BorderLayout.CENTER);
      pack();
    }

    JButton createButton(String lable){
      JButton button=new JButton(lable);
      button.addActionListener(this);
      return button;
    }
    JButton createButton(ImageIcon icon){
      JButton button=new JButton(icon);
      button.addActionListener(this);
      return button;
    }
    public void setNameField(String name){
      nameField.setText(name);
    }
    public void selectType(String tempName){
      StringBuffer sb=new StringBuffer();
      switch(typeList.getSelectedIndex()){
	case 0: sb.append("public class "+tempName+" {\n\tpublic "+tempName+"() {\n\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew "
		  +tempName+"();\n\t}\n}");
	        break;
        case 1: sb.append("public abstract class "+tempName+" {\n\tpublic "+tempName+"() {\n\n\t}\n\n}");
	        break;
	case 2: sb.append("public interface "+tempName+"{\n\n}");
	        break;
	case 3: sb.append("import javax.swing.*;\nimport java.awt.event.*;\nimport java.awt.*;\n\npublic class "
	          +tempName+" extends JFrame {\n\tpublic "
                  +tempName+"() {\n\t\tsuper();\n\n\t\tsetBounds(10,10,400,400);\n\t\tsetVisible(true);\n\t\taddWindowListener(new WindowAdapter() {\n\t\t\tpublic void windowClosing(WindowEvent e) {\n\t\t\t\tSystem.exit(0);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew "
		  +tempName+"();\n\t}\n}");
        break;
	default: System.out.println("none");break;
      }
      viewArea.setText(sb.toString());
    }

    public File showDialog(String title){
      files.setDialogTitle(title);
      files.setFileSelectionMode(files.DIRECTORIES_ONLY);
      files.rescanCurrentDirectory();

      int result=files.showDialog(frame,null);

      return (result==files.APPROVE_OPTION)?files.getSelectedFile():null;
    }

    public void actionPerformed(ActionEvent e){
      Object source=e.getSource();
      if(source==ok){
        if(!dirField.getText().equals("")&&nameField.getText().length()>5){
	  int i=0;
	  while(i<=frame.getTab().getTabCount()-1){
	    if(frame.getTab().getTitleAt(i++).equals(nameField.getText())){
	      JOptionPane.showMessageDialog(frame,"The file has already opened");
	      return;
	    }
	  }
	  if(new File(dirField.getText(),nameField.getText()).exists())
	    if(JOptionPane.NO_OPTION==JOptionPane.showConfirmDialog(frame,
	                                                         "The file has existed.Overwrite?",
								 "File has existed",
	                                                         JOptionPane.YES_NO_OPTION,
		                                                 JOptionPane.WARNING_MESSAGE))return;
          frame.setDirection(dirField.getText());
          InterWindow interWindow = new InterWindow(frame);
	  interWindow.getTextArea().setText(viewArea.getText());
	  DefaultMutableTreeNode node=new DefaultMutableTreeNode(nameField.getText());
          frame.getTab().addTab(nameField.getText(),interWindow);
          frame.getTab().setSelectedIndex(frame.getTab().getTabCount()-1);
	  frame.getFileTree().getRoot().add(node);
	  frame.getFileTree().getTree().updateUI();
          frame.getSaveItem().setEnabled(false);
          frame.getObs().addObserver((Observer)interWindow);
          frame.setTitle(nameField.getText());
	  File dirFile=new File(dirField.getText());
	  if(!dirFile.exists())dirFile.mkdir();
	  frame.getSaveItem().saveFile();
	  frame.getStatusBar().getSystemDirection().setText("D: "+dirField.getText());
	  setVisible(false);

	  if(frame.getTab().getTabCount()>0){
            frame.getSaveAsItem().setEnabled(true);
	    frame.getSaveAllItem().setEnabled(true);
            frame.getCloseItem().setEnabled(true);
	    frame.getCloseAllItem().setEnabled(true);
	    frame.getFindItem().setEnabled(true);
	    frame.getFindNextItem().setEnabled(true);
	    frame.getCompileItem().setEnabled(true);
	    frame.getRunItem().setEnabled(true);
	    frame.getCopyItem().setEnabled(true);
	    frame.getCutItem().setEnabled(true);
	    frame.getPasteItem().setEnabled(true);
	    frame.getUndoItem().setEnabled(true);
	    frame.getRedoItem().setEnabled(true);
          }
	}else if(nameField.getText().length()<=5) JOptionPane.showMessageDialog(frame,"input file name!","Warning",JOptionPane.WARNING_MESSAGE);
	else if(dirField.getText().equals("")) JOptionPane.showMessageDialog(frame,"The Direction isn't exist!","Warning",JOptionPane.WARNING_MESSAGE);
      }else if(source==cancel)setVisible(false);
      else if(source==choose){
        File file=showDialog("Choose Direction:");
	if(file!=null){
	  dirField.setText(file.getPath());
	  frame.setDirection(file.getPath());
	}
      }
    }
  }
}
